package com.miao.teacher.ui;

import org.json.JSONException;
import org.json.JSONObject;
import com.espeaker.sdk.Constants;
import com.espeaker.sdk.api.LoginApi;
import com.espeaker.sdk.api.MiaoApi;
import com.espeaker.sdk.api.VersionApi;
import com.espeaker.sdk.utils.JsonUtils;
import com.espeaker.sdk.utils.TimeUtil;
import com.miao.teacher.app.ApplicationMain;
import com.miao.teacher.app.TApp;
import com.miao.teacher.models.VersionInfo;
import com.miao.teacher.presenters.OnMenuClickedListener;
import com.miao.teacher.presenters.OnMenuSelectListener;
import com.miao.teacher.utils.DBUtil;
import com.miao.teacher.utils.FileUtil;
import com.miao.teacher.utils.TMediaPlayer;
import com.miao.teacher.widget.ExamplePlayer;
import com.miao.teacher.widget.TSlidingMenu;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MiaoActivity extends BaseFragmentActivity implements
		OnMenuClickedListener, OnMenuSelectListener {
	/** Called when the activity is first created. */
	private TSlidingMenu menu = null;
	private LoginApi api = new LoginApi();

	private VersionApi versionApi = new VersionApi();

	private AlertDialog alertDialog = null;
	
	private AlertDialog hetongDialog=null;
	
	public static boolean isForeground = false;
	
	public boolean mIsShowHeTong=false;
	/*
	 * 创建实例
	 */
	public static void createInstance(Context context) {
		Intent intent = new Intent();
		intent.setClass(context, MiaoActivity.class);
		context.startActivity(intent);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		isForeground = false;
		/* JPushInterface.onPause(this); */
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isForeground = true;
		/*
		 * JPushInterface.onResume(this);
		 * JPushInterface.resumePush(getApplicationContext());
		 */
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		// super.onBackPressed();
		if (menu.getMenu().isMenuShowing()) {
			menu.getMenu().showContent();
		} else {
			super.onBackPressed();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.frame_content);

		FragmentTransaction fragmentTransaction = getSupportFragmentManager()
				.beginTransaction();
		MenuFragment menuFragment = new MenuFragment();
		fragmentTransaction.replace(R.id.menu, menuFragment);
		fragmentTransaction.replace(R.id.content, new MainFragment());
		fragmentTransaction.commit();
		menu = new TSlidingMenu(this);
		ApplicationMain.getInstance().addActivity(this);
		String userName = FileUtil.getPreferences(this, TApp.Account_KEY);
		((TextView) findViewById(R.id.tv_title)).setText("你好啊， " + userName
				+ "老师");
		versionApi.getCurVersion(mHandler);
		new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				new DBUtil(MiaoActivity.this);
			}
		}.start();

		findViewById(R.id.btnShowMenu).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (menu.getMenu().isMenuShowing()) {
							menu.getMenu().showContent();
						} else {
							menu.getMenu().showMenu();
						}
					}
				});
		String isFirst = FileUtil.getPreferences(this, TApp.IS_FIRST_KEY);
		if (isFirst == null) {
			//showHeTong();
			showExample();
			FileUtil.addPreferences(MiaoActivity.this, TApp.IS_FIRST_KEY, "1");
		}
		if(MiaoApi.IsDebug)
		{
			ToastShowMsg("这是测试版本");
		}
		new DBUtil(MiaoActivity.this).updateDBVersion();
	}

	@Override
	public void onMenuButtonClicked() {
		// TODO Auto-generated method stub
		if (menu.getMenu().isMenuShowing()) {
			menu.getMenu().showContent();
		} else {
			menu.getMenu().showMenu();
		}
	}

	@Override
	public void OnMenuSelected(int position) {
		// TODO Auto-generated method stub
		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();
		Fragment newFragment = null;
		switch (position) {
		case 0:
			newFragment = MainFragment.newInstance();
			break;
		case 1:
			newFragment = HistoryFragment.newInstance();
			break;
		case 2:
			newFragment = FeedbackFragment.newInstance();
			break;
		case 3:
			// newFragment = ExampleFragment.newInstance();
			if (menu.getMenu().isMenuShowing()) {
				menu.getMenu().showContent();
			}
			showExample();
			break;
		case 4:
			newFragment = RulesFragment.newInstance();
			break;
		case 5:
			if (menu.getMenu().isMenuShowing()) {
				menu.getMenu().showContent();
			}
			changePassword();
			break;
		case 6:
			if (menu.getMenu().isMenuShowing()) {
				menu.getMenu().showContent();
			}
			logOut();
			break;
		}
		if (newFragment != null) {
			transaction.replace(R.id.content, newFragment);
			transaction.addToBackStack(null);
			transaction.commit();
			menu.getMenu().showContent();
		}
	}

	private void logOut() {
		new AlertDialog.Builder(MiaoActivity.this).setTitle("退出登录").setMessage(
				"确定退出登录").setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// JPushInterface.stopPush(getApplicationContext());
						ApplicationMain.getInstance().AppExit();
					}
				}).setNegativeButton("取消",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				}).show();
	}

	/*
	 * 修改密码
	 */
	private void changePassword() {
		alertDialog = new AlertDialog.Builder(MiaoActivity.this,
				R.style.AlertDialog).create();
		alertDialog.show();
		final Window window = alertDialog.getWindow();
		window.setContentView(R.layout.layout_change_password);
		LayoutParams lp = window.getAttributes();
		lp.width = getXPx() - 20;
		window.setAttributes(lp);
		window.findViewById(R.id.img_close).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						alertDialog.dismiss();
					}
				});
		window.findViewById(R.id.btnCancel).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						alertDialog.dismiss();
					}
				});

		window.findViewById(R.id.btnOk).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						String account = ((EditText) window
								.findViewById(R.id.edt_account)).getText()
								.toString();
						String oldPass = ((EditText) window
								.findViewById(R.id.edt_old_pass)).getText()
								.toString();
						String newPass = ((EditText) window
								.findViewById(R.id.edt_new_pass)).getText()
								.toString();
						String confirmPass = ((EditText) window
								.findViewById(R.id.edt_confirm_pass)).getText()
								.toString();
						if (TextUtils.isEmpty(account)) {
							ToastShowMsg(R.string.str_change_pass_account_empty);
							return;
						}
						if (TextUtils.isEmpty(oldPass)) {
							ToastShowMsg(R.string.str_change_pass_old_empty);
							return;
						}
						if (TextUtils.isEmpty(newPass)) {
							ToastShowMsg(R.string.str_change_pass_new_empty);
							return;
						}
						if (TextUtils.isEmpty(confirmPass)) {
							ToastShowMsg(R.string.str_change_pass_confirm_empty);
							return;
						}
						if (!newPass.equals(confirmPass)) {
							ToastShowMsg(R.string.str_change_pass_new_pass_err);
							return;
						}
						api.changePass(account, oldPass, newPass, mHandler);

					}
				});
		alertDialog.getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
	}

	/*
	 * 修改密码返回结果
	 */
	private void changePassResult(Object obj) {
		try {
			JSONObject json = new JSONObject(obj.toString());
			int status = JsonUtils.getInt(json, "status", -1);
			if (status == 404) {
				ToastShowMsg(R.string.str_login_account_noexit);
			} else if (status == 403) {
				ToastShowMsg(R.string.str_login_password_error);
			} else if (status == 0) {
				ToastShowMsg(R.string.str_change_pass_change_success);
				if (alertDialog != null) {
					alertDialog.dismiss();
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * 显示Toast
	 */
	protected void ToastShowMsg(int resId) {
		Toast
				.makeText(MiaoActivity.this, getResources().getString(resId),
						3000).show();
	}

	@Override
	protected void RecMsgFromHandler(Message msg) {
		// TODO Auto-generated method stub
		super.RecMsgFromHandler(msg);
		switch (msg.what) {
		case Constants.GET_VERSION:
			UpdateVersion(msg.obj);
			break;
		case Constants.USER_CHANGE_PASS:
			changePassResult(msg.obj);
			break;
		case TApp.GOLDACTIVITY_PLAYFINISH:
			if (playAnim != null) {
				playAnim.stop();
			}
			break;
		}
	}

	/*
	 * 接收到版本更新信息
	 */
	private void UpdateVersion(Object obj) {
		try {
			JSONObject json = new JSONObject(obj.toString());
			int status = JsonUtils.getInt(json, "status", -1);
			if (status == 0) {
				ToastShowMsg(R.string.str_login_success);
				JSONObject json2 = JsonUtils
						.getJSONObject(json, "values", null);
				VersionInfo Info = new VersionInfo();
				Info.version = JsonUtils.getInt(json2, "version", 0);
				Info.version_name = JsonUtils.getString(json2, "version_name");
				Info.info = JsonUtils.getString(json2, "info");
				Info.url = JsonUtils.getString(json2, "url");
				Info.must_update = JsonUtils.getInt(json2, "must_update", 0);
				AskUpdate(Info);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * 处理版本更新信息
	 */
	private void AskUpdate(final VersionInfo info) {
		try {
			PackageManager packageManager = getPackageManager();
			PackageInfo packInfo = packageManager.getPackageInfo(
					getPackageName(), 0);
			int version = packInfo.versionCode;
			if (info.version > version) {
				new AlertDialog.Builder(MiaoActivity.this).setTitle("版本更新啦")
						.setMessage(info.info).setPositiveButton("现在更新",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										downLoadApk(info.url);
									}
								}).setNegativeButton("以后更新",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										if (info.must_update == 1) {
											ApplicationMain.getInstance()
													.AppExit();
										}
									}
								}).show();
			}
		} catch (Exception er) {
		}
	}

	/*
	 * 获取屏幕宽度 px
	 */
	protected int getXPx() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		dm = this.getApplicationContext().getResources().getDisplayMetrics();
		return dm.widthPixels;
	}

	private AlertDialog exampleDialog = null;
	public String[] exampleArr = new String[] { "c_1.amr", "r_2.amr",
			"c_3.amr", "r_4.amr", "c_5.amr", "r_6.amr", "c_7.amr", "r_8.amr",
			"c_9.amr", "r_10.amr", "c_11.amr", "r_12.amr", "c_13.amr",
			"r_14.amr", "c_15.amr" };
	public String overallAmr = "r_overall.amr";
	public String suggestionAmr = "r_suggestion.amr";
	AnimationDrawable playAnim = null;
	TMediaPlayer mVoicePlayer = null;
	ImageView animComment;
	ImageView animAdvise;
	ExamplePlayer p;
	View playVoice;
	/*
	 * 显示示例
	 */
	private void showExample() {
		exampleDialog = new AlertDialog.Builder(MiaoActivity.this,
				R.style.AlertDialog).create();
		exampleDialog.show();
		final Window window = exampleDialog.getWindow();
		window.setContentView(R.layout.layout_example);
		LayoutParams lp = window.getAttributes();
		lp.width = getXPx() - 20;
		lp.height = getYPx() * 3 / 4;
		window.setAttributes(lp);
		initView(window);

	}
	private void showHeTong()
	{
		mIsShowHeTong=true;
		hetongDialog = new AlertDialog.Builder(MiaoActivity.this,
				R.style.AlertDialog).create();
		hetongDialog.setCanceledOnTouchOutside(false);
		hetongDialog.show();
		final Window window = hetongDialog.getWindow();
		window.setContentView(R.layout.dialog_hetong);
		LayoutParams lp = window.getAttributes();
		lp.width = getXPx() - 20;
		lp.height = getYPx() -20;
		window.setAttributes(lp);
		WebView webView = (WebView) window.findViewById(R.id.webView);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.loadUrl("http://miao.yishuodian.com/laoshihetong.html?time="+TimeUtil.getCurrentTimeStamp());
		window.findViewById(R.id.btnCancel).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						mIsShowHeTong=false;
						hetongDialog.dismiss();
						ApplicationMain.getInstance().AppExit();
					}
				});

		window.findViewById(R.id.btnOk).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						mIsShowHeTong=false;
						hetongDialog.dismiss();
						showExample();
						FileUtil.addPreferences(MiaoActivity.this, TApp.IS_FIRST_KEY, "1");
					}
				});
		hetongDialog.setOnDismissListener(new OnDismissListener(){

			@Override
			public void onDismiss(DialogInterface dialog) {
				// TODO Auto-generated method stub
				if(mIsShowHeTong){
					ApplicationMain.getInstance().AppExit();
				}
			}
			
		});
	}
	private void initView(final Window view) {
		mVoicePlayer = new TMediaPlayer();
		final LinearLayout lly = (LinearLayout) view
				.findViewById(R.id.lly_timeline);
		ImageView cImg = (ImageView) view.findViewById(R.id.c_seekbar);
		ImageView rImg = (ImageView) view.findViewById(R.id.r_seekbar);
		p = new ExamplePlayer(this, mHandler, exampleArr,
				getXPx() - dip2px(32), lly, cImg, rImg);
		playVoice=view.findViewById(R.id.btnPlayerPlay);
		playVoice.setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (p.isPlaying()) {
							p.doPause();
							playVoice.setBackgroundDrawable(
											getResources().getDrawable(
													R.drawable.iv_audio_play));
						} else {
							if (playAnim != null) {
								playAnim.stop();
							}
							mVoicePlayer.DoStop();
							p.doRestart();
							playVoice.setBackgroundDrawable(
											getResources().getDrawable(
													R.drawable.iv_audio_pause));
						}
					}
				});
		
		view.findViewById(R.id.img_close).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						p.doStop();
						exampleDialog.dismiss();
						mVoicePlayer.DoStop();
					}
				});
		final LinearLayout llyAudio = (LinearLayout) view
				.findViewById(R.id.lly_audio_comment);
		final LinearLayout llyAudioAdvise = (LinearLayout) view
				.findViewById(R.id.lly_audio_advise);
		animComment = (ImageView) view.findViewById(R.id.imgAudio_comment);
		animAdvise = (ImageView) view.findViewById(R.id.imgAudio_advise);
		llyAudio.setOnClickListener(new CommentPlay());
		llyAudioAdvise.setOnClickListener(new AdvisePlay());
		exampleDialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				try {
					p.doStop();
					mVoicePlayer.DoStop();
				} catch (Exception er) {
				}
			}

		});
	}

	/*
	 * 播放评论录音
	 */
	class CommentPlay implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			try {
				AssetManager assetManager = getAssets();
				AssetFileDescriptor afd = assetManager
						.openFd("r/" + overallAmr);
				mVoicePlayer.ASycPlay(afd, mHandler);
				animComment
						.setBackgroundResource(R.drawable.anim_revise_playing);
				if (playAnim != null) {
					playAnim.stop();
				}
				playAnim = (AnimationDrawable) animComment.getBackground();
				playAnim.start();
				if (p.isPlaying()) {
					p.doPause();
					playVoice.setBackgroundDrawable(
									getResources().getDrawable(
											R.drawable.iv_audio_play));
				}
			} catch (Exception er) {
			}
		}

	}

	/*
	 * 播放建议录音
	 */
	class AdvisePlay implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			try {
				AssetManager assetManager = getAssets();
				AssetFileDescriptor afd = assetManager.openFd("r/"
						+ suggestionAmr);
				mVoicePlayer.ASycPlay(afd, mHandler);
				animAdvise
						.setBackgroundResource(R.drawable.anim_revise_playing);
				if (playAnim != null) {
					playAnim.stop();
				}
				playAnim = (AnimationDrawable) animAdvise.getBackground();
				playAnim.start();
				if (p.isPlaying()) {
					p.doPause();
					playVoice.setBackgroundDrawable(
									getResources().getDrawable(
											R.drawable.iv_audio_play));
				}
			} catch (Exception er) {
			}
		}

	}

}